#!/usr/bin/env node

/**
 * Docker 容器内 OpenAI API 连接测试脚本
 * 用于诊断容器网络连接问题
 */

const https = require('https');
const http = require('http');
const { URL } = require('url');

// 从环境变量获取配置
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const OPENAI_BASE_URL = process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1';
const OPENAI_MODEL = process.env.OPENAI_MODEL || 'gpt-4o-mini';

console.log('🔍 Docker 容器内 OpenAI API 连接测试');
console.log('=====================================');
console.log(`📍 容器环境信息:`);
console.log(`   - NODE_ENV: ${process.env.NODE_ENV}`);
console.log(`   - HOSTNAME: ${process.env.HOSTNAME}`);
console.log(`   - PWD: ${process.env.PWD}`);
console.log('');

console.log(`🌐 OpenAI 配置:`);
console.log(`   - API Key: ${OPENAI_API_KEY ? OPENAI_API_KEY.substring(0, 10) + '...' : '❌ 未设置'}`);
console.log(`   - Base URL: ${OPENAI_BASE_URL}`);
console.log(`   - Model: ${OPENAI_MODEL}`);
console.log('');

if (!OPENAI_API_KEY) {
    console.error('❌ 错误: OPENAI_API_KEY 环境变量未设置');
    process.exit(1);
}

// 解析 URL
let apiUrl;
try {
    apiUrl = new URL(OPENAI_BASE_URL);
    console.log(`🔗 解析的 URL 信息:`);
    console.log(`   - 协议: ${apiUrl.protocol}`);
    console.log(`   - 主机: ${apiUrl.hostname}`);
    console.log(`   - 端口: ${apiUrl.port || (apiUrl.protocol === 'https:' ? 443 : 80)}`);
    console.log(`   - 路径: ${apiUrl.pathname}`);
    console.log('');
} catch (error) {
    console.error('❌ URL 解析失败:', error.message);
    process.exit(1);
}

// 测试函数
async function testConnection() {
    console.log('🔌 开始连接测试...');
    console.log('');

    // 1. DNS 解析测试
    console.log('1️⃣ DNS 解析测试');
    try {
        const dns = require('dns').promises;
        const addresses = await dns.lookup(apiUrl.hostname);
        console.log(`   ✅ DNS 解析成功: ${apiUrl.hostname} -> ${addresses.address}`);
    } catch (error) {
        console.error(`   ❌ DNS 解析失败: ${error.message}`);
        return;
    }

    // 2. 基础网络连接测试
    console.log('');
    console.log('2️⃣ 基础网络连接测试');
    const isHttps = apiUrl.protocol === 'https:';
    const port = apiUrl.port || (isHttps ? 443 : 80);
    
    try {
        await testTcpConnection(apiUrl.hostname, port);
        console.log(`   ✅ TCP 连接成功: ${apiUrl.hostname}:${port}`);
    } catch (error) {
        console.error(`   ❌ TCP 连接失败: ${error.message}`);
        return;
    }

    // 3. HTTP/HTTPS 请求测试
    console.log('');
    console.log('3️⃣ HTTP/HTTPS 请求测试');
    try {
        const response = await makeHttpRequest('GET', `${OPENAI_BASE_URL}/models`, {
            'Authorization': `Bearer ${OPENAI_API_KEY}`,
            'Content-Type': 'application/json'
        });
        
        if (response.statusCode === 200) {
            console.log('   ✅ HTTP 请求成功');
            const data = JSON.parse(response.body);
            console.log(`   📊 可用模型数量: ${data.data ? data.data.length : '未知'}`);
            
            // 检查目标模型是否可用
            if (data.data) {
                const targetModel = data.data.find(model => model.id === OPENAI_MODEL);
                if (targetModel) {
                    console.log(`   ✅ 目标模型 "${OPENAI_MODEL}" 可用`);
                } else {
                    console.log(`   ⚠️  目标模型 "${OPENAI_MODEL}" 不在可用列表中`);
                    console.log(`   📝 可用模型示例: ${data.data.slice(0, 3).map(m => m.id).join(', ')}`);
                }
            }
        } else {
            console.error(`   ❌ HTTP 请求失败: ${response.statusCode} ${response.statusMessage}`);
            console.error(`   📄 响应内容: ${response.body.substring(0, 500)}`);
            return;
        }
    } catch (error) {
        console.error(`   ❌ HTTP 请求异常: ${error.message}`);
        return;
    }

    // 4. OpenAI Chat API 测试
    console.log('');
    console.log('4️⃣ OpenAI Chat API 测试');
    try {
        const testPayload = {
            model: OPENAI_MODEL,
            messages: [
                {
                    role: 'user',
                    content: '请简单回复"测试成功"'
                }
            ],
            max_tokens: 10,
            temperature: 0
        };

        const response = await makeHttpRequest('POST', `${OPENAI_BASE_URL}/chat/completions`, {
            'Authorization': `Bearer ${OPENAI_API_KEY}`,
            'Content-Type': 'application/json'
        }, JSON.stringify(testPayload));

        if (response.statusCode === 200) {
            const data = JSON.parse(response.body);
            const message = data.choices?.[0]?.message?.content || '无响应';
            console.log('   ✅ Chat API 测试成功');
            console.log(`   💬 AI 响应: "${message.trim()}"`);
            console.log(`   📊 使用的 tokens: ${data.usage?.total_tokens || '未知'}`);
        } else {
            console.error(`   ❌ Chat API 测试失败: ${response.statusCode}`);
            console.error(`   📄 错误响应: ${response.body.substring(0, 500)}`);
        }
    } catch (error) {
        console.error(`   ❌ Chat API 测试异常: ${error.message}`);
    }

    console.log('');
    console.log('🎉 测试完成！');
}

// TCP 连接测试
function testTcpConnection(hostname, port) {
    return new Promise((resolve, reject) => {
        const net = require('net');
        const socket = new net.Socket();
        
        const timeout = setTimeout(() => {
            socket.destroy();
            reject(new Error(`连接超时 (${hostname}:${port})`));
        }, 10000);

        socket.connect(port, hostname, () => {
            clearTimeout(timeout);
            socket.destroy();
            resolve();
        });

        socket.on('error', (error) => {
            clearTimeout(timeout);
            reject(error);
        });
    });
}

// HTTP 请求封装
function makeHttpRequest(method, url, headers = {}, body = null) {
    return new Promise((resolve, reject) => {
        const urlObj = new URL(url);
        const isHttps = urlObj.protocol === 'https:';
        const client = isHttps ? https : http;
        
        const options = {
            hostname: urlObj.hostname,
            port: urlObj.port || (isHttps ? 443 : 80),
            path: urlObj.pathname + urlObj.search,
            method: method,
            headers: {
                'User-Agent': 'AIDE-Docker-Test/1.0',
                ...headers
            },
            timeout: 30000
        };

        if (body) {
            options.headers['Content-Length'] = Buffer.byteLength(body);
        }

        const req = client.request(options, (res) => {
            let responseBody = '';
            
            res.on('data', (chunk) => {
                responseBody += chunk;
            });
            
            res.on('end', () => {
                resolve({
                    statusCode: res.statusCode,
                    statusMessage: res.statusMessage,
                    headers: res.headers,
                    body: responseBody
                });
            });
        });

        req.on('error', (error) => {
            reject(error);
        });

        req.on('timeout', () => {
            req.destroy();
            reject(new Error('请求超时'));
        });

        if (body) {
            req.write(body);
        }
        
        req.end();
    });
}

// 运行测试
if (require.main === module) {
    testConnection().catch(error => {
        console.error('');
        console.error('💥 测试过程中发生未捕获的错误:');
        console.error(error);
        process.exit(1);
    });
}
